Le module sympy (calcul formel)

In [1]:
from sympy import *
In [2]:
x=symbols("x")
In [10]:
f=S("2/3*x**2+3*x-5")
print(f)
f
2*x**2/3 + 3*x - 5
Out[10]:
$\displaystyle \frac{2 x^{2}}{3} + 3 x - 5$

Calcul littéral

In [34]:
2*x+3*x
Out[34]:
$\displaystyle 5 x$
In [36]:
factor(x**2+5*x-6)
Out[36]:
$\displaystyle \left(x - 1\right) \left(x + 6\right)$
In [38]:
simplify(1/x+1/(x+1))
Out[38]:
$\displaystyle \frac{2 x + 1}{x \left(x + 1\right)}$
In [41]:
expand((x-2)*(x+3))
Out[41]:
$\displaystyle x^{2} + x - 6$
In [44]:
f=x**2+5*x-6
f.subs(x,sqrt(2))
Out[44]:
$\displaystyle -4 + 5 \sqrt{2}$

Dérivation et intégration

In [11]:
g =diff(f,x)
print(g)
g
4*x/3 + 3
Out[11]:
$\displaystyle \frac{4 x}{3} + 3$
In [12]:
integrate(g,x)
Out[12]:
$\displaystyle \frac{2 x^{2}}{3} + 3 x$

Les fractions

In [6]:
Rational("2/7")+Rational("4/9")
Out[6]:
$\displaystyle \frac{46}{63}$
In [7]:
a=S("2/7+4/9")
simplify(a)
Out[7]:
$\displaystyle \frac{46}{63}$

Les matrices

In [28]:
A = Matrix([[1,2],[4,2]])
A
Out[28]:
$\displaystyle \left[\begin{matrix}1 & 2\\4 & 2\end{matrix}\right]$
In [29]:
B=Matrix([[1,3],[2,1]])
B
Out[29]:
$\displaystyle \left[\begin{matrix}1 & 3\\2 & 1\end{matrix}\right]$
In [26]:
A+B
Out[26]:
$\displaystyle \left[\begin{matrix}2 & 5\\6 & 3\end{matrix}\right]$
In [27]:
A*B
Out[27]:
$\displaystyle \left[\begin{matrix}5 & 5\\8 & 14\end{matrix}\right]$
In [30]:
5*A
Out[30]:
$\displaystyle \left[\begin{matrix}5 & 10\\20 & 10\end{matrix}\right]$
In [31]:
A**(-1)
Out[31]:
$\displaystyle \left[\begin{matrix}- \frac{1}{3} & \frac{1}{3}\\\frac{2}{3} & - \frac{1}{6}\end{matrix}\right]$
In [32]:
A.transpose()
Out[32]:
$\displaystyle \left[\begin{matrix}1 & 4\\2 & 2\end{matrix}\right]$
In [ ]: